package com.mybatis.executor;

import com.mybatis.config.JdbcProperties;
import com.mybatis.binding.MapperStatement;
import com.mybatis.resultset.ResultSetHandler;
import com.mysql.cj.util.StringUtils;


import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author luoc
 * @version 1.0
 * @date 2021/2/20 14:44
 * @since 1.0
 */
public class SimpleExecutor<T> implements Executor {
    private JdbcProperties jdbcProperties;
    private ResultSetHandler resultSetHandler;


    public SimpleExecutor(JdbcProperties jdbcProperties) {
        this.jdbcProperties = jdbcProperties;
    }

    public SimpleExecutor(JdbcProperties jdbcProperties,ResultSetHandler resultSetHandler) {
        this.jdbcProperties = jdbcProperties;
        this.resultSetHandler = resultSetHandler;
    }

    public <E> List<E> query(MapperStatement ms, Object parameter) {
        List<E> ret = new ArrayList<E>();
        // 具体方法待实现

        try {
            Class.forName(jdbcProperties.getDriver());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection connection = null;
        PreparedStatement preparedStatement =null;
        ResultSet resultSet = null;

        try {
            // 获取连接
            connection = DriverManager.getConnection(jdbcProperties.getUrl()
                    ,jdbcProperties.getUsername(),jdbcProperties.getPassword());
            // 预编译sql语句
            preparedStatement =  connection.prepareStatement(ms.getSql());
            // 处理sql语句中的占位符
            if (parameter !=null ){
                parameterize(preparedStatement, parameter);
            }
            // 执行sql语句
            resultSet = preparedStatement.executeQuery();
            // 处理结果
            resultSetHandler.handlerResultSet(resultSet, ret, ms.getResultType());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return ret;
    }

    /**
     *  设置参数
     * @param preparedStatement 预编译
     * @param parameter 参数
     * @throws SQLException
     */
    private void parameterize(PreparedStatement preparedStatement,Object parameter) throws SQLException {
        if (parameter instanceof String){
            preparedStatement.setString(1, (String) parameter);
        }else if (parameter instanceof Long){
            preparedStatement.setLong(1, (Long) parameter);
        }else if (parameter instanceof Integer){
            preparedStatement.setInt(1, (Integer) parameter);
        }
    }




}
